package horncomb.bpm.process.def.state;

import horncomb.bpm.BpmContextHolder;
import horncomb.bpm.process.core.ProcessDefinition;
import horncomb.bpm.process.core.StateDefinition;

import java.io.Serializable;

import org.springframework.util.StringUtils;

/**
 * @author Daniel
 */
public abstract class AbstractStateDefinition implements StateDefinition,
		Serializable {
	private static final long serialVersionUID = -2128646509375454222L;
	protected String id;
	private String name;
	private String processDefinitionId;
	transient ProcessDefinition processDefinition;

	/**
	 *
	 */
	public AbstractStateDefinition() {
		super();
	}

	/**
	 * {@inheritDoc}
	 */
	public String getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(String id) {
		this.id = id;
	}

	/**
	 * {@inheritDoc}
	 */
	public String getName() {
		return StringUtils.hasText(name) ? name : this.getId();
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the processDefinition
	 */
	public ProcessDefinition getProcessDefinition() {
		if (processDefinition == null) {
			this.processDefinition = BpmContextHolder.getContext()
					.getProcessManagementService().findProcessDefinition(
							this.processDefinitionId);
		}
		return this.processDefinition;
	}

	/**
	 * @param processDefinition
	 *            the processDefinition to set
	 */
	public void setProcessDefinition(ProcessDefinition processDefinition) {
		this.processDefinition = processDefinition;
		this.processDefinitionId = processDefinition.getId();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	/**
	 * @return the processDefinitionId
	 */
	public String getProcessDefinitionId() {
		return processDefinitionId;
	}

	/**
	 * @param processDefinitionId
	 *            the processDefinitionId to set
	 */
	public void setProcessDefinitionId(String processDefinitionId) {
		this.processDefinitionId = processDefinitionId;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		DefaultStateDefinition other = (DefaultStateDefinition) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String toString() {
		return this.getId();
	}
}